<template>
    <PlayGround v-if="$store.state.pk.status === 'playing'  " />
    <!-- <PlayGround></PlayGround> -->
    <MatchGround v-if="$store.state.pk.status === 'matching' " />
    <!-- 注意,在模板中(即<template>里面)引用全局变量要用$,在script中不用加 -->
    <ResultBoard v-if="$store.state.pk.loser != 'none' " />
</template>


<script>
import PlayGround from "@/components/PlayGround.vue"
import { onMounted, onUnmounted } from "vue";
// onMounted: 当组件被挂载完成后执行的函数;onUnmonted: 当组件被卸载的时候执行的函数
import { useStore } from "vuex" //引入全局变量
import MatchGround from '../../components/MatchGround.vue'
import ResultBoard from '../../components/ResultBoard.vue'

export default {
    components: {
        MatchGround,
        PlayGround,
        ResultBoard,
    },
    setup() {
        const store = useStore();//拿出全局变量
        //字符串中有${}表达式操作的话要用``，不能用引号（这里是测试用，所以先不传token，传id）
        const socketUrl = `ws://127.0.0.1:3000/websocket/${store.state.user.token}/`;
        
        store.commit("updateLoser","none");//一局游戏开始前，清空失败者（否则重新开始游戏时，可能有遗留上一局的结果界面）
        store.commit("updateIsRecord",false);//设定当前是要搞游戏，区别于搞录像
        let socket = null;
        onMounted(() => { //当当前页面打开时调用（实际是当前组件被挂载完成后调用）
            
            //调试用：此时未完成匹配功能，暂时自己搞一个默认的对手信息
            store.commit("updateOpponent",{
                username: "我的对手",
                photo: "https://cdn.acwing.com/media/article/image/2022/08/09/1_1db2488f17-anonymous.png"
                // photo: "https://ts1.cn.mm.bing.net/th/id/R-C.d0b4575b4afe749d07fdc60de9e899d6?rik=qB4Hjjq7IEIr2Q&riu=http%3a%2f%2fupload.taihainet.com%2f2016%2f0924%2f1474726868882.jpeg&ehk=ePw2Jq8Dq3kncd1HUoFCs09yIZMEVwOiAktMi5mxRyc%3d&risl=&pid=ImgRaw&r=0"
            })
            socket = new WebSocket(socketUrl); //js自带的WebSocket()
            socket.onopen = () => { //连接成功时调用的函数
                console.log("connected!");
                store.commit("updateSocket",socket);//链接一成功，就把链接存到全局变量里面
            }

            socket.onmessage = msg => { //前端接收到信息时调用的函数，msg是后端传来的数据
                const data = JSON.parse(msg.data); //拿到数据（不同的框架数据定义的格式不一样）
                if (data.event === "start-matching") { //这个这个start-matching是respA或respB返回的
                    console.log("刚收到时的对手坦克种类"+data.opponent_kind);
                //匹配成功,更新对手信息
                    store.commit("updateOpponent",{
                        id: data.opponent_id,
                        username: data.opponent_username,
                        photo: data.opponent_photo,
                        kind:data.opponent_kind,
                        });
                    setTimeout(() => {//等两秒，再跳转
                        store.commit("updateStatus","playing");//匹配完成后自动跳转到pk界面
                    },2000); //延时函数，单位是毫秒
                    // store.commit("updateGamemap",data.gamemap);//此时收到从后端来的地图，要把它存入全局变量
                    // console.log(data.game)
                    // store.commit("updateGame",data.game)//此时收到从后端来的地图，要把它存入全局变量
                    }else if (data.event === "move") {//如果后端发来的信息类型是move
                        // console.log(data);
                        
                        const game = store.state.pk.gameObject;//把GameMap.js对象从全局变量中取出来
                        // console.log(data.status+"-"+data.direction);
                        const [playerA, playerB] = game.players;//获取该对象中的两条蛇参数。(按照设置，1就是A，2就是B)
                        if(store.state.pk.opponent_kind==="playerA"){
                            if(playerA){
                                playerA.set_direction(data.direction);
                                playerA.set_status(data.status);
                            }
                            
                        }else{
                            if(playerB){
                                playerB.set_direction(data.direction);
                                playerB.set_status(data.status);
                            }
                        }
                    } else if(data.event === "stop"){
                        const game = store.state.pk.gameObject;//把GameMap.js对象从全局变量中取出来
                        const [playerA, playerB] = game.players;//获取该对象中的两条蛇参数。
                        if(store.state.pk.opponent_kind==="playerA"){
                            if(playerA){
                                playerA.set_status(data.status);
                            }
                            
                        }else{
                            if(playerB){
                                playerB.set_status(data.status);
                            }
                        }
                    }else if (data.event === "shoot") {

                        const game = store.state.pk.gameObject;//把GameMap.js对象从全局变量中取出来
                        const [playerA, playerB] = game.players;//获取该对象中的两条蛇参数。
                        if(store.state.pk.opponent_kind==="playerA"){
                            if(playerA){
                                playerA.attack();
                            }
                        }else{
                            if(playerB){
                                playerB.attack();
                            }
                        }
                    }else if (data.event === "updateModel") {
                        console.log("我收到发射指令了")
                        let game = store.state.pk.gameObject;//把GameMap.js对象从全局变量中取出来

                        let [playerA, playerB] = game.players;//获取该对象中的两条蛇参数。
                        let walls = game.walls;
                        let model_str = data.model.split("#");
                        console.log(model_str);
                        for(let wall_index in walls){//改变墙
                            if(model_str[0][wall_index]==='1'){
                                walls[wall_index].set_status("die");
                            }
                        }

                        if(store.state.pk.opponent_kind==="playerA"){//只让对手坦克接受坦克改变状态
                            if(playerA){
                                if(model_str[1]==='1')
                                    playerA.set_status("die");
                                else
                                    playerA.set_rc(parseFloat(model_str[2]),parseFloat(model_str[3]));
                            }
                        }else{
                            if(playerB){
                                if(model_str[4]==='1')
                                    playerB.set_status("die");
                                else
                                    playerB.set_rc(parseFloat(model_str[5]),parseFloat(model_str[6]));
                            }
                        }
                    }
            }

            socket.onclose = () => { //链接断开时调用的函数
                store.commit("updateStatus", "matching");//链接断开时，匹配也自动断开，重回匹配页面
                console.log("disconnected!");
            }
        });

        onUnmounted(() => { //当当前页面关闭时调用
            
            socket.close(); //卸载的时候断开连接，实际在这里调用了上面onclose后面的函数
            //注意一定要手动断开链接，否则会一直创建新连接
        });
    }
}


</script>


<style scoped>
</style>
